package com.geen.tuoke.utils

import android.app.Activity
import android.app.ProgressDialog
import com.geen.tuoke.R
import com.geen.tuoke.bean.UpdateInfo
import com.liulishuo.okdownload.DownloadTask
import com.liulishuo.okdownload.core.cause.EndCause
import com.liulishuo.okdownload.core.cause.ResumeFailedCause
import com.liulishuo.okdownload.core.listener.DownloadListener1
import com.liulishuo.okdownload.core.listener.assist.Listener1Assist
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction
import com.geen.tuoke.utils.ext.toastShort
import java.io.File

/***
 * app更新逻辑
 * @property downloadTask DownloadTask?
 * @property installFile File?
 * @property quDialog QMUIDialog?
 * @property qmProgress ProgressDialog?
 */
class UpdateAppUtils() {

    private var downloadTask: DownloadTask? = null
    private var installFile: File? = null
    private var quDialog: QMUIDialog? = null
    private var qmProgress :ProgressDialog? = null


    /***
     * 检查更新
     * @param updateInfo UpdateInfo
     */
    fun showUpdateDialog(updateInfo: UpdateInfo, activity: Activity) {
        val appVersion = AppUtil.getVersionCode()
        var isForceUpdate = false
        if (appVersion < updateInfo.lastVersionCount) {
            isForceUpdate = true
        }
        val dialogBuilder = QMUIDialog.MessageDialogBuilder(activity)
            .setTitle("版本更新" + updateInfo.currentVersion)
            .setMessage(updateInfo.content)
        //版本更新条件
        if (appVersion < updateInfo.versionCount || isForceUpdate) {
            if (isForceUpdate) {
                quDialog = dialogBuilder
                    .addAction(
                        0,
                        R.string.text_update,
                        QMUIDialogAction.ACTION_PROP_NEGATIVE
                    ) { _, _ ->
                        downLoadApp(updateInfo.versionLink,activity)
                    }.create()
                quDialog?.setCancelable(false)
                quDialog?.setCanceledOnTouchOutside(false)
            } else {
                quDialog = dialogBuilder.addAction(
                    R.string.text_cancel
                ) { dialog, index -> dialog.dismiss() }
                    .addAction(
                        0,
                        R.string.text_update,
                        QMUIDialogAction.ACTION_PROP_NEGATIVE
                    ) { _, _ ->
                        //todo 下载app
                        downLoadApp(updateInfo.versionLink,activity)
                    }.create()
            }
            quDialog?.show()
        }
    }

    private fun downLoadApp(url: String,activity: Activity) {
        //如果已经下载成功，直接安装
        if (installFile != null) {
            AppUtil.installApk(installFile)
            return
        }
        if (url.isNullOrEmpty()) {
            return
        }
        val appStoragePath = activity.getExternalFilesDir("")
        if (appStoragePath == null) {
            toastShort("没有获取到可存储的区域")
            return
        }
        downloadTask = DownloadTask.Builder(
            url, appStoragePath.absolutePath, "xxx.apk"
        )
            .setMinIntervalMillisCallbackProcess(300) // do re-download even if the task has already been completed in the past.
            .setPassIfAlreadyCompleted(false)
            .setConnectionCount(1)
            .build()

        downloadTask?.enqueue(object : DownloadListener1() {
            override fun taskStart(task: DownloadTask, model: Listener1Assist.Listener1Model) {
                qmProgress = ProgressDialog(activity)
                qmProgress?.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
                qmProgress?.setProgressNumberFormat("")
                qmProgress?.show()
            }

            override fun taskEnd(
                task: DownloadTask,
                cause: EndCause,
                realCause: java.lang.Exception?,
                model: Listener1Assist.Listener1Model
            ) {
                qmProgress?.dismiss()
                when (cause) {
                    EndCause.COMPLETED -> {
                        toastShort("下载完成")
                        installFile = task.file
                        AppUtil.installApk(task.file)
                    }
                    else -> {
                        toastShort("下载失败,请重试")
                    }
                }
            }

            override fun progress(task: DownloadTask, currentOffset: Long, totalLength: Long) {
                val progress =
                    Math.min((currentOffset * 100 / totalLength).toInt(), 99)
                qmProgress?.progress = progress
            }

            override fun connected(
                task: DownloadTask,
                blockCount: Int,
                currentOffset: Long,
                totalLength: Long
            ) {
            }

            override fun retry(task: DownloadTask, cause: ResumeFailedCause) {
            }
        })
    }

    fun isUpdateDialogShowing():Boolean{
        var isShowing = false
        quDialog?.let {
            isShowing = it.isShowing
        }
        return isShowing
    }
}